package org.inote.utils;

import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;

/**
 * 短信验证工具类
 *
 * 使用说明：
 *  可调用方法：
 *  1.sendPhoneCode(String phone)   给指定手机号发送默认
 *  2.sendPhoneCode(String phone, int numCount)
 *
 * @author HUAWEI
 */
public class PhoneCodeUtil {

    /**
     * api调用所需AccessKry
     */
    private static String accessKey;
    /**
     * api调用所需AppCode
     */
    private static String appCode;

    /**
     * 短信验证码默认位数
     */
    private static final int DEFAULT_NUM_COUNT = 4;

    /**
     * 获取api调用所需的AccessKey和AppCode（测试版）
     */
    static {
        accessKey = "3bb4a55234bc4e3b9feccd093a452150";
        appCode = "24b89ac1fa50419bb3fdefee208f236f";
    }

    /**
     * 供内部方法获取AccessKey（测试版）
     * @return
     */
    private static String getAccessKey() {
        return accessKey;
    }

    /**
     * 供内部方法获取AppCode（测试版）
     * @return
     */
    private static String getAppCode() {
        return appCode;
    }

    /**
     * 发送默认位数的短信验证码
     * @param phone
     */
    public static String sendPhoneCode(String phone){
        return sendPhoneCode(phone, DEFAULT_NUM_COUNT);
    }

    /**
     * 发送指定位数的短信验证码（测试版）
     * @param phone
     * @param numCount
     */
    public static String sendPhoneCode(String phone, int numCount){
        if (!StringFormUtil.isPhone(phone))
            return null;
        if (numCount <= 0)
            return null;
        String phoneCode = RandomUtil.getRandomStringNumber(numCount);
        return sendPhoneCodeAPI(phone, phoneCode, getAccessKey(), getAppCode());
    }

    /**
     * 发送短信验证码API调用
     * 调用api
     * @param phone 手机号
     * @param phoneCode 验证码
     */
    private static String sendPhoneCodeAPI(String phone, String phoneCode, String accessKey, String appCode) {
        String path = "https://dfsms.api.bdymkt.com/send_sms";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        request.setCredentials(accessKey, appCode);

        // 设置header参数
        request.addHeaderParameter("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");



        // 设置jsonBody参数
        String jsonBody = "phone_number=" + phone + "&template_id=TPL_0001&content=code:" + phoneCode + ",expire_at:5";
        request.setJsonBody(jsonBody);

        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
            System.out.println(response.getResult());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return phoneCode;
    }

}
